package org.example.laboratorymanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.laboratorymanagement.mapper.HomeworkMapper;
import org.example.laboratorymanagement.pojo.Homework;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.service.HomeworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HomeworkServiceImpl implements HomeworkService {

    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public PageBean pageHomeworks(Integer page, Integer pageSize, String username, String lesson,
                                  String susername, String experiment, String local, String date, String time) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 查询实验报告
        List<Homework> list = homeworkMapper.listHomeworks(username, lesson, susername, experiment, local, date, time);
        Page<Homework> p = (Page<Homework>) list;

        // 封装PageBean对象
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());

        return pageBean;
    }

    @Override
    public void insert(Homework homework) {
        homeworkMapper.insert(homework);
    }

    @Override
    public void update(Homework homework) {
        homeworkMapper.update(homework);
    }

    @Override
    public void delete(List<Integer> ids) {
        homeworkMapper.delete(ids);
    }

    @Override
    public void insertBatch(List<Homework> homeworks) {
        // 关闭session的自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            HomeworkMapper homeworkMapper = sqlSession.getMapper(HomeworkMapper.class);
            homeworks.stream().forEach(homework -> homeworkMapper.insert(homework));
            // 提交数据
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }

    }
}
